package cn.moefly.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.util.Optional;

public class InstantCustomDeserializer extends JsonDeserializer<Instant> {

    /**
     * 1973-03-03 17:46:39 in ms
     * 5138-11-16 17:46:39 in sec
     */
    private static final long SECOND_MILLIS_BORDER = 99999999999L;


    @Override
    public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return Optional.ofNullable(p.getValueAsLong())
                .map(InstantCustomDeserializer::longToLocalDateTome)
                .orElse(null);
    }

    private static Instant longToLocalDateTome(long milli){
        Instant instant;
        if (milli < SECOND_MILLIS_BORDER){
            instant = Instant.ofEpochSecond(milli);
        } else {
            instant = Instant.ofEpochMilli(milli);
        }
        return instant;
    }

    public static Instant srtToInstant(String milli){
        return longToLocalDateTome(Long.parseLong(milli));
    }
}
